﻿using Microsoft.AspNetCore.Http;
using System.IO;
using System.Text.RegularExpressions;

namespace RayD.Core
{
    /// <summary>
    /// HttpContext容器
    /// </summary>
    public class HttpContextHelper
    {
        static HttpContextHelper()
        {
            httpContextAccessor = ServiceContainer.Current.GetInstance<IHttpContextAccessor>();
        }

        private static IHttpContextAccessor httpContextAccessor;


        /// <summary>
        /// 获取HttpContext（单元测试时需赋值,其余情况请勿赋值）
        /// </summary>
        public static HttpContext Instance
        {
            set
            {
                //单元测试使用
                httpContextAccessor.HttpContext = value;
            }
            get
            {
                return httpContextAccessor.HttpContext;
            }
        }


        /// <summary>
        /// 获取请求Body
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static string GetRequestBody(HttpRequest request = null)
        {
            if (request.IsEmpty())
            {
                request = Instance.Request;
            }
            var sr = new StreamReader(request.Body);
            string requestParams = sr.ReadToEndAsync().Result;
            if (!string.IsNullOrEmpty(requestParams))
            {
                request.Body.Position = 0;
            }
            return requestParams;
        }
    }
}
